package golf.stockdata.framework.spring;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;

import org.apache.log4j.Logger;

public class ApplicationServiceProcessor {
	
	private static Logger logger = Logger.getLogger(ApplicationServiceProcessor.class);
	
	private static Random randomGenerator = new Random();
	
	private static HashMap<Integer, ApplicationObjectContainer> aocPool = new HashMap<Integer, ApplicationObjectContainer>();
	
	private static int AOC_POOL_SIZE = 10;
	
	static{
		logger.debug(">>> static");
		logger.debug("Initializing AOC pool");
		for(int i=0;i<AOC_POOL_SIZE;i++){
			ApplicationObjectContainer aoc = new ApplicationObjectContainer(String.valueOf(i));
			aocPool.put(i, aoc);
		}
		logger.debug("<<< static");
	}
	
	/**
	 * 
	 * @param svcType
	 * @param request - for ability calls, pass the interface name.
	 * @param response
	 */
	public void invokeApplicationService(ServiceType svcType, Object request, Object response){
		logger.debug(">>> invokeApplicationService");
		
		ApplicationObjectContainer aoc = getAOC();
		
		if(svcType.equals(ServiceType.ABILITY)){
			logger.debug("calling ability");
		}else if(svcType.equals(ServiceType.SERVICE)){
			logger.debug("calling service");
		}
		
		logger.debug("<<< invokeApplicationService");
	}
	
	public static ApplicationObjectContainer getAOC(){
		
		logger.debug(">>> getAOC");
		
		ApplicationObjectContainer aocOut = null;
		
		while(aocOut == null){
			
			Iterator<Integer> itr = aocPool.keySet().iterator();
			synchronized (aocPool) {
				while(itr.hasNext()){
					int aocID = itr.next();
					ApplicationObjectContainer aocTmp = aocPool.get(aocID);
					if(!aocTmp.inUsed){
						logger.debug("returning AOC:" + aocID);
						aocOut = aocTmp;
						aocOut.inUsed = true;
						break;
					}
				}
			}
			
			int waitTime = randomGenerator.nextInt(250);
			try {
				Thread.sleep(waitTime);
			} catch (InterruptedException e) {
				logger.warn(e);
			}
			
		}
		
		logger.debug("<<< getAOC");
		return aocOut;
		
	}
}
